package com.uzai.console.web.wxpub;

import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.console.dto.wxpub.WxpubAccredit;
import com.uzai.console.service.wxpub.WxpubService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号回调函数
 * @author lucher
 * @date 2022/2/27 15:20
 */
@Api(value = "微信公众号回调接口",tags = "云监控|报警联系人", hidden = true)
@ApiSort(19)
@Controller
public class WxpubCallbackController {
    private static Logger logger = LoggerFactory.getLogger(WxpubCallbackController.class);
    @Resource
    private WxpubService wxpubService;

    @ApiOperation(value = "回调接口", hidden = true)
    @RequestMapping(value = "/wx/access")
    @ResponseBody
    public void access(WxpubAccredit accredit, HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        String method = request.getMethod();
        if (method.toUpperCase().equals("GET")){         // 接入认证
            try {
                String echostr = wxpubService.accredit(accredit).toString();
                response.getWriter().write(echostr);
                //return null;
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }else if(method.toUpperCase().equals("POST")){   // 消息
            Map<String,String> params = parseParams(request);
            logger.info("param :{}",params);
            Object msg = wxpubService.msg(params);
            if (msg!=null){
                try {
                    PrintWriter out = response.getWriter();
                    out.print(msg);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                }
            }
            //return null;
        }
        //return null;
    }

    //处理微信公众号参数信息
    public static Map<String,String> parseParams(HttpServletRequest request){
        Map<String,String> messageMap=new HashMap<String, String>();
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            Element root = document.getRootElement();
            List<Element> elementsList=root.elements();
            for(Element e:elementsList){
                logger.info(e.getName()+":"+e.getText());
                messageMap.put(e.getName(),e.getText());
            }
        } catch (IOException e) {
            logger.error("IOException:{}",e);
        } catch (DocumentException e) {
            logger.error("DocumentException:{}",e);
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    inputStream=null;
                }
            }
        }
        return messageMap;
    }

}
